package auth

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"goAdminV1/api/auth/v1"
	"goAdminV1/utility"
	"strings"
	"time"
)

func (c *ControllerV1) LoginOut(ctx context.Context, req *v1.LoginOutReq) (res *v1.LoginOutRes, err error) {
	// 1. 获取请求头中的 Authorization 令牌
	r := ghttp.RequestFromCtx(ctx)
	tokenString := r.Header.Get("Authorization")
	if tokenString == "" {
		return nil, gerror.New("missing authorization header")
	}

	// 去除 Bearer 前缀
	parts := strings.SplitN(tokenString, " ", 2)
	if len(parts) != 2 || parts[0] != "Bearer" {
		return nil, utility.Error(utility.CodeOperation, gerror.New("无效的 Authorization 头格式"))
	}
	token := strings.TrimSpace(parts[1]) // 去除 Token 左右的空格和换行

	// 解析令牌获取过期时间
	claims, err := utility.ParseToken(ctx, token)
	if err != nil {
		return nil, err
	}
	expiration := time.Unix(claims.ExpiresAt.Unix(), 0)

	// 将令牌添加到黑名单
	utility.AddToBlacklist(token, expiration)

	return &v1.LoginOutRes{}, nil
}
